<template>
  <div class="app-container">
    <el-form
      ref="form"
      :model="Form"
      :rules="rules"
      class="FormStyle"
      label-width="120px"
    >
      <div class="itemStyle">
        <el-form-item label="菜品名称:" prop="name" class="formStyle">
          <el-input
            v-model="Form.name"
            placeholder="请填写菜品名称"
            class="input1Style"
          />
        </el-form-item>
        <el-form-item label="菜品分类:">
          <el-select
            v-model="Form.categoryId"
            placeholder="请选择菜品分类"
            class="input1Style"
          >
            <el-option
              v-for="(item, index1) in dishList"
              :key="index1"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="菜品价格:"
          prop="price"
          width="300"
          class="formStyle"
        >
          <el-input
            v-model.number="Form.price"
            placeholder="请设置菜品价格"
            class="input1Style"
          />
        </el-form-item>
      </div>
      <el-form-item label="口味做法配置:" class="tasteStyle">
        <el-form-item>
          <div class="flavorBox">
            <span 
            v-if="dishFlavors.length == 0"
            class="addTaste" 
            @click="addFlavore"
            >+ 添加口味</span>
            <div 
              class="flavour" 
              v-if="dishFlavors.length != 0"
            >
              <div class="title">
                <span>口味名称 && 口味标签(点击即可添加)</span>
              </div>
              <div class="cont">
                <div 
                  v-for="(item, index) in dishFlavors" 
                  :key="index" 
                  class="items"
                >
                  <div class="itTit">
                    <div class="selectInput">
                      <div>
                        <el-input
                          v-model="item.name"
                          type="text"
                          style="width: 100%"
                          placeholder="请输入口味"
                          @focus="selectFlavor(true,index)"
                          @blur="outSelect(false,index)"
                          @input="inputHandle(index)"
                        />
                      </div>
                      <div v-show="item.showOption" class="flavorSelect">
                        <span
                          v-for="(it, ind) in dishFlavorsData"
                          :key="ind"
                          class="items"
                          @click="checkOption(it,ind,index)"
                        >{{ it.name }}</span>
                        <span
                          v-if="dishFlavorsData == []"
                          class="none"
                        >无数据</span>
                      </div>
                    </div>
                  </div>
                  <div
                    class="labItems"
                    style="display: flex"
                  >
                    <span
                      v-for="(it, ind) in item.value"
                      :key="ind"
                    >{{ it }} <i @click="delFlavorLabel(index, ind)">X</i></span>
                    <div
                      class="inputBox"
                      :style="inputStyle"
                      contenteditable="true"
                      @focus="flavorPosition(index)"
                      @keydown.enter="(val)=>keyDownHandle(val,index)"
                    ></div>
                  </div>
                  <span
                    class="delFlavor delBut non"
                    @click="delFlavor(index)"
                  >删除</span>
                </div>
                <div
                  class="addTaste1"
                  @click="addFlavore"
                >添加口味</div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form-item>
      <el-form-item label="菜品图片:" prop="image">
        <el-upload
          class="avatar-uploader"
          :action="`${env}/common/upload`"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <div class="address">
        <el-form-item label="菜品描述:" prop="region">
          <el-input
            v-model="Form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述,最长不超过200字"
            maxlength="200"
            class="textareaStyle"
          />
        </el-form-item>
      </div>
      <el-form-item class="buttonStyle">
        <el-button 
          @click="onCancel" 
          class="button1Style"
        >Cancel</el-button>
        <el-button 
          @click="onSubmit" 
          type="primary"
          class="button2Style"
        >Save</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  queryDishById,
  getDishesList,
  addDishes,
  editDishes,
} from "@/api/dishes";
export default {
  data() {
    return {
      env: process.env.VUE_APP_BASE_API,
      imageUrl: "",
      restKey: 0,
      id: "",
      textarea: "",
      action: "",
      value: "",
      submitType: "",
      dishList: [],
      dishFlavorsData: [],
      dishFlavors: [],
      vueRest: '1',
      index : 0,
      inputStyle  : {'flex': 1},
      inputVisible: false,
      inputValue: "",
      Form: {
        name: '',
        id: '',
        price: '',
        code: '',
        image: '',
        description: '',
        dishFlavors: [],
        status: 1,
        categoryId: '',
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("价格必须填写"));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        categoryId: [
          {'required': true, 'message': '请选择菜品分类', 'trigger': 'change'}
        ],
      },
    };
  },
  created() {
    const {
      query: { action, id },
    } = this.$route;
    this.action = action;
    this.id = id;
    if (this.action === "EDIT" && id) {
      this.fechData();
    }
    this.getDishList();
    this.getFlavorListHand();
  },
  methods: {
    handleAvatarSuccess(res) {
      this.Form.image = res.data;
      this.imageUrl = this.env + `/common/download?name=${res.data}`;
    },
    async fechData() {
      queryDishById(this.id).then((res) => {
        console.log(res);
        this.Form = { ...res.data };
        this.imageUrl = this.env + `/common/download?name=${res.data.image}`;
        this.dishFlavors = res.data.flavors && res.data.flavors.map(obj => ({ ...obj, value: JSON.parse(obj.value), showOption: false }))
        this.Form.status = res.data.status == '1'
        this.Form.price = String(res.data.price / 100);
      });
    },
    addFlavore () {
      this.dishFlavors.push({'name': '', 'value': [], showOption: false}) // JSON.parse(JSON.stringify(this.dishFlavorsData))
    },
    delFlavor (ind) {
      this.dishFlavors.splice(ind, 1)
    },
        // 获取口味列表
    getFlavorListHand () {
        // flavor flavorData
      this.dishFlavorsData = [
        {'name':'甜味','value':['无糖','少糖','半糖','多糖','全糖']},
        {'name':'温度','value':['热饮','常温','去冰','少冰','多冰']},
        {'name':'忌口','value':['不要葱','不要蒜','不要香菜','不要辣']},
        {'name':'辣度','value':['不辣','微辣','中辣','重辣']}
      ]
    },
    //口味位置记录
    flavorPosition (index) {
      this.index = index
    },
      // 添加口味标签
    keyDownHandle (val,index) {
      if (val.target.innerText.trim() != '') {
        this.dishFlavors[index].value.push(val.target.innerText)
        val.target.innerText = ''
      }
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    delFlavorLabel (index, ind) {
      this.dishFlavors[index].value.splice(ind, 1)
    },
    deleteFlavour(index1) {
      this.flavors.splice(index1, 1);
    },
    addFlavour() {
      this.flavors.push({});
    },
    getDishList() {
      getDishesList({ type: 1 })
        .then((res) => {
          this.dishList = res.data;
        })
        .catch((err) => {
          this.$message.error("操作失败" + err);
        });
    },
    selectFlavor(st,index){
      console.log('st',st)
      console.log('index',index)
      console.log('this.dishFlavors',this.dishFlavors)
      const obj = JSON.parse(JSON.stringify(this.dishFlavors[index]))
      obj.showOption = st
      this.dishFlavors.splice(index,1,obj)
      // this.dishFlavors[index].showOption = st
    },
    outSelect(st,index){
      const _this = this
      setTimeout(()=> {
        const obj = JSON.parse(JSON.stringify(_this.dishFlavors[index]))
        obj.showOption = st
        _this.dishFlavors.splice(index,1,obj)
      }, 200)
    },
    checkOption(val, ind, index){
      this.selectHandle(val.name, index, ind)
      this.dishFlavors[index].name = val.name
    },
    selectHandle(val, key, ind){
      const arrDate = [...this.dishFlavors]
      arrDate[key] = JSON.parse(JSON.stringify(this.dishFlavorsData[ind]))
      this.dishFlavors = arrDate
    },
    onCancel() {
      this.$router.go(-1);
    },
    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let params = {...this.Form}
          params.status = this.Form ? 1 : 0
          params.price *= 100
          params.categoryId = this.Form.categoryId
          params.flavors = this.dishFlavors.map(obj => ({ ...obj, value: JSON.stringify(obj.value) }))
          delete params.dishFlavors
          if (this.action == "EDIT" && this.id) {
            await editDishes(params);
            this.$message.success("修改成功!");
          } else {
            delete params.id
            await addDishes(params);
            this.$message.success("添加成功!");
          }
          this.$router.push('/dishes')
        }
      })
    }
  }
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss" scoped>
.app-container {
  width: 100%;
  height: 100%;
  background-color: #fff;
  .FormStyle {
    margin-left: 80px;
    .itemStyle {
      margin-top: 20px;
      .input1Style {
        width: 40% !important;
        font-size: 16px;
      }
    }
    .tasteStyle {
      .flavorBox{
        width: 1000px;
        .flavour {
          border: solid 1px #dfe2e8;
          border-radius: 3px;
          padding: 15px;
          width: 85%;
          background: #fafafb;
          .title {
            margin: 0px 10px;
            color: rgba(0, 0, 0, 0.5);
          }
          .cont {
            .items {
              display: flex !important;
              margin: 10px 0;
              .itTit{
                width: 150px;
                margin-right: 15px;
                .selectInput{
                  position: relative;
                  width: 100%;
                  min-width: 100px;
                  .flavorSelect {
                    position: absolute;
                    width: 100%;
                    padding: 0 10px;
                    border-radius: 3px;
                    border: solid 1px pink;
                    line-height: 30px;
                    text-align: center;
                    background: #fff;
                    top: 50px;
                    z-index: 99;
                    .items {
                      cursor: pointer;
                      display: inline-block;
                      width: 100%;
                      line-height: 35px;
                      border-bottom: solid 1px #f4f4f4;
                      color: #666;
                    }
                    .none{
                      font-size: 14px;
                    }
                  }
                }
              }
              .labItems{
                flex: 1;
                display: flex;
                flex-wrap: wrap;
                border-radius: 3px;
                min-height: 39px;
                border: solid 1px #d8dde3;
                background: #fff;
                padding: 0 5px;
                span {
                  display: inline-block;
                  color: #f19c59;
                  margin: 5px;
                  line-height: 26px;
                  height: 26px;
                  padding: 0 10px;
                  background: #fdf4eb;
                  border-radius: 3px;
                  border: solid 1px #fae2cd;
                  i {
                    cursor: pointer;
                    font-style: normal;
                  }
                }
                .inputBox{
                  display: inline-block;
                  width: 100%;
                  height: 36px;
                  line-height: 36px;
                  overflow: hidden;
                }
              }
              .delFlavor{
                  display: inline-block;
                  padding: 0 10px;
                  font-size:18px;
                  color: red;
                  cursor: pointer;
                }
            }
            .addTaste1{
              width: 150px;
              height: 60px;
              text-align: center;
              line-height: 60px;
              border-radius: 10px;
              cursor: pointer;
              font-size: 18px;
              background-color: pink;
              color: rgba(0, 0, 0, 0.5);
            }
            .addTaste1:hover {
              background-color: rgb(251, 207, 215);
            }
          }
        } 
      }
      .addTaste {
        padding: 15px 15px;
        text-align: center;
        border-radius: 10px;
        cursor: pointer;
        font-size: 18px;
        background-color: pink;
        color: rgba(0, 0, 0, 0.5);
      }
      .addTaste:hover {
        background-color: rgb(251, 207, 215);
      }
    }
    .address {
      margin: 20px 10px 20px 0;
      height: 100px;
      width: 800px;
      .textareaStyle {
        height: 100%;
        width: 650px;
      }
    }
    .buttonStyle {
      margin-left: 500px;
      margin-top: 80px;
      .button1Style {
        width: 120px;
        height: 50px;
        font-size: 20px;
        color: grey;
      }
      .button1Style:hover {
        border-color: rgb(249, 222, 227);
        color: white;
        background-color: rgb(249, 222, 227);
      }
      .button2Style {
        width: 120px;
        height: 50px;
        font-size: 20px;
        background-color: pink;
        color: grey;
        border: none;
      }
      .button2Style:hover {
        color: white;
      }
    }
  }
}
</style>
